package listener;

import javax.servlet.ServletContext;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

@WebListener
public class OnlineCountListener implements HttpSessionListener {
    //创建session监听: 看你的一举一动
    //一旦创建一个session，就会触发一次这个
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
        //要想统计session，作用域要提到最高
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        System.out.println(httpSessionEvent.getSession().getId());
        Integer onlineCount= (Integer) servletContext.getAttribute("OnlineCount");

        if(onlineCount==null){
            onlineCount = 1;
        }else{
            int count = onlineCount;
            onlineCount = count + 1;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount", onlineCount);
    }
    //销毁session监听
    //一旦session销毁，就会触发
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        ServletContext servletContext = httpSessionEvent.getSession().getServletContext();
        Integer onlineCount= (Integer) servletContext.getAttribute("onlineCount");

        if(onlineCount==null){
            onlineCount = 0;
        }else{
            int count = onlineCount;
            onlineCount = count - 1;
        }
        //每次都在更新自己,有累加
        servletContext.setAttribute("OnlineCount", onlineCount);

    }
}